﻿@model ReservedNamespaceViewModel
@{
    ViewBag.Title = "Reserved Namespaces";
}

@ViewHelpers.AjaxAntiForgeryToken(Html)

<section role="main" class="container main-container">

    <div class="row">
        <div class="col-xs-12">
            <div class="message-container" data-bind="visible: message">
                @ViewHelpers.AlertInfo(@<text><span class="message" data-bind="text: message"></span></text>)
            </div>
            <h2>Reserve namespace</h2>
            <form data-bind="submit: prefixSearch">
                <div class="row-checkbox-label">
                    <input type="text" class="input-brand" placeholder="Specific namespace" autocomplete="on" autofocus data-bind="value: prefixSearchQuery" />
                    <input type="submit" class="btn btn-brand" value="Search" title="Search" />
                </div>
            </form>
            <br />

            <div data-bind="visible: allPrefixResults().length > 0">
                @using (Html.BeginForm())
                {
                    <div id="prefixResult" data-bind="foreach: allPrefixResults">
                        <table aria-label="Reserved Namespaces Search Results">
                            <tr>
                                <td>
                                    <span style="font-weight: bold">Details:</span>
                                    <div style="margin-left: 20px">
                                        <div>
                                            <span style="font-weight: bold">Namespace: </span>
                                            <span data-bind="text: $data.prefix.Value" />
                                        </div>
                                        <div>
                                            <label class="brand-checkbox">
                                                <input type="checkbox" data-bind="checked: $data.prefix.IsSharedNamespace, disable: $data.isExisting" />
                                                <span>IsSharedNamespace</span>
                                            </label>
                                        </div>
                                        <div>
                                            <label class="brand-checkbox">
                                                <input type="checkbox" data-bind="checked: $data.prefix.IsPrefix, disable: $data.isExisting" value="IsPrefix" />
                                                <span>IsPrefix</span>
                                            </label>
                                        </div>
                                        <div>
                                            <span style="font-weight: bold">Matching Pattern: </span>
                                            <span data-bind="text: $data.pattern" />
                                        </div>
                                        <!-- ko if: $data.parents.length > 0 -->
                                        <div>
                                            <span style="font-weight: bold">⚠ Parent namespaces:</span>
                                            <ul>
                                                <!-- ko foreach: $data.parents -->
                                                <li data-bind="text: $data"></li>
                                                <!-- /ko -->
                                            </ul>
                                        </div>
                                        <!-- /ko -->
                                        <!-- ko if: $data.isExisting -->
                                        <input style="margin-top: 5px" class="btn btn-brand-danger" type="submit" value="Deallocate Namespace" title="Delete this namespace"
                                               data-bind="click: $parent.managePrefix.bind(this, $data.prefix, false, $data.parents)" />
                                        <!-- /ko -->
                                        <!-- ko ifnot: $data.isExisting -->
                                        <input style="margin-top: 5px" class="btn btn-brand" type="submit" value="Reserve Namespace" title="Add this namespace"
                                               data-bind="click: $parent.managePrefix.bind(this, $data.prefix, true, $data.parents)" />
                                        <!-- /ko -->
                                    </div>
                                </td>
                                <td style="vertical-align: top">
                                    <!-- ko if: $data.isExisting -->
                                    <span style="font-weight: bold">Owners:</span>
                                    <div style="margin-left: 20px">
                                        <div id="prefixOwners" data-bind="foreach: $data.owners">
                                            <div style="margin: 5px" class="row-checkbox-label">
                                                <a href="#" target="_blank" data-bind="text: $data, attr: { href: $root.generateUserUrl($data) }"></a>
                                                <input style="float: right" type="button" class="btn btn-brand" value="Remove" title="Remove this owner" data-bind="click: $root.removeOwner.bind(this, $data, $parent.prefix)" />
                                            </div>
                                        </div>
                                        <div class="row-checkbox-label" style="margin: 5px">
                                            <input type="text" class="input-brand" placeholder="Enter username" autocomplete="off" data-bind="value: $parent.newOwner, valueUpdate: 'afterkeydown'" />
                                            <input type="button" class="btn btn-brand" value="Add" title="Add new owner for this prefix" data-bind="click: $parent.addOwner.bind(this, $data.prefix), enable: $parent.newOwner().length > 0" />
                                        </div>
                                    </div>
                                    <!-- /ko -->
                                </td>
                            </tr>
                        </table>
                    </div>
                }
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-xs-12">
            <h2>Find namespaces by prefix</h2>
            <form method="get" action="@Url.Action("FindNamespacesByPrefix")">
                <div class="row-checkbox-label">
                    <input type="text" class="input-brand" placeholder="Namespace prefix" autocomplete="on" name="prefix" value="@Model.ReservedNamespacesQuery" />
                    <input type="submit" class="btn btn-brand" value="Search" />
                </div>
            </form>
            <br />
            @if (Model.ReservedNamespaces != null)
            {
                if (Model.ReservedNamespaces.Count == 0)
                {
                    <p>No reserved namespaces found.</p>
                }
                else
                {
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Value</th>
                                <th>IsSharedNamespace</th>
                                <th>IsPrefix</th>
                                <th>Owners</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach (var rn in Model.ReservedNamespaces)
                            {
                                <tr>
                                    <td>@(rn.Value + (rn.IsPrefix ? "*" : ""))</td>
                                    <td>@rn.IsSharedNamespace</td>
                                    <td>@rn.IsPrefix</td>
                                    <td>
                                        @foreach (var owner in rn.Owners)
                                        {
                                            <a href="@Url.User(owner)">@owner.Username</a>
                                        }
                                    </td>
                                </tr>
                            }
                        </tbody>
                    </table>
                }
            }
        </div>
    </div>

    <div class="row">
        <div class="col-xs-12">
            <h2>Find package registrations by prefix</h2>
            <form method="get" action="@Url.Action("FindPackagesByPrefix")">
                <div class="row-checkbox-label">
                    <input type="text" class="input-brand" placeholder="Package ID prefix" autocomplete="on" name="prefix" value="@Model.PackageRegistrationsQuery" />
                    <input type="submit" class="btn btn-brand" value="Search" />
                </div>
            </form>
            <br />
            @if (Model.PackageRegistrations != null)
            {
                if (Model.PackageRegistrations.Count == 0)
                {
                    <p>No package registrations found.</p>
                }
                else
                {
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Package ID</th>
                                <th>IsVerified</th>
                                <th>Download count</th>
                                <th>Owners</th>
                                <th>Reserved Namespaces</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach (var pr in Model.PackageRegistrations)
                            {
                            <tr>
                                <td><a href="@Url.Package(pr.Id)">@pr.Id</a></td>
                                <td>
                                    @if (pr.IsVerified)
                                    {
                                        <i class="ms-Icon ms-Icon--SkypeCircleCheck reserved-indicator" title="@Strings.ReservedNamespace_ReservedIndicatorTooltip" alt="Reserved namespace icon"></i>
                                    }
                                </td>
                                <td>@pr.DownloadCount.ToNuGetNumberString()</td>
                                <td>
                                    @foreach (var owner in pr.Owners)
                                    {
                                        <a href="@Url.User(owner)">@owner.Username</a>
                                    }
                                </td>
                                <td>
                                    @foreach (var rn in pr.ReservedNamespaces)
                                    {
                                        @(rn.Value + (rn.IsPrefix ? "* " : " "))
                                    }
                                </td>
                            </tr>
                            }
                        </tbody>
                    </table>
                }
            }
        </div>
    </div>
</section>

@section BottomScripts {
    <script>
        $(document).ready(function () {
            var viewModel = function () {
                var $self = this;

                this.message = ko.observable('');
                this.prefixSearchQuery = ko.observable('');
                this.newOwner = ko.observable('');

                this.refresh = function () {
                    this.prefixSearch();
                }

                this.allPrefixResults = ko.observableArray([]);
                this.prefixSearch = function () {
                    $self.message("");
                    $self.newOwner("");
                    $.ajax({
                        url: '@Url.Action("SearchPrefix", "ReservedNamespace", new {area = "Admin"})?query=' + encodeURIComponent($self.prefixSearchQuery()),
                        cache: false,
                        dataType: 'json',
                        success: function (data) {
                            $self.allPrefixResults.removeAll();
                            if (!data.success && data.message != null) {
                                $self.message(data.message);
                            } else {

                                for (var i = 0; i < data.Prefixes.length; i++) {
                                    var resultModel = data.Prefixes[i];
                                    resultModel.pattern = ko.computed(function () {
                                        return $self.generatePattern(resultModel.prefix.Value, resultModel.prefix.IsPrefix);
                                    }, resultModel);
                                }

                                $self.allPrefixResults(data.Prefixes);
                            }
                        }
                    })
                    .fail(function(jqXhr, textStatus, errorThrown) {
                        alert("Error: " + errorThrown);
                    });
                };

                this.managePrefix = function (prefixToModify, addPrefix, parents, model, e) {
                    if (!addPrefix && !confirm('Are you sure you want to delete this namespace?')) {
                        e.preventDefault();
                        return;
                    }

                    if (addPrefix
                        && parents.length > 0
                        && !confirm("At least one parent namespace exists. Ensure the owners of the parent namespaces have approved of the new child namespace. Press 'OK' to continue. Existing parent(s):\n" + parents.join("\n"))) {
                        e.preventDefault();
                        return;
                    }

                    var url = addPrefix
                        ? '@Url.Action("AddNamespace", "ReservedNamespace", new { area = "Admin" })'
                        : '@Url.Action("RemoveNamespace", "ReservedNamespace", new { area = "Admin" })';
                    $self.message("");
                    $.ajax({
                        url: url,
                        cache: false,
                        dataType: 'json',
                        type: 'POST',
                        data: window.nuget.addAjaxAntiForgeryToken(prefixToModify),
                        success: function (data) {
                            if (data.success) {
                                $self.refresh();
                            }

                            if (data.message != null) {
                                $self.message(data.message);
                            }
                        }
                    })
                    .fail(function (jqXhr, textStatus, errorThrown) {
                        alert("Error: " + errorThrown);
                    });
                };

                this.addOwner = function (prefix) {
                    var owner = $self.newOwner();
                    var obj = {
                        prefix: prefix,
                        owner: owner,
                    };

                    $self.message("");
                    $.ajax({
                        url: '@Url.Action("AddOwner", "ReservedNamespace", new { area = "Admin" })',
                        cache: false,
                        dataType: 'json',
                        type: 'POST',
                        data: window.nuget.addAjaxAntiForgeryToken(obj),
                        success: function (data) {
                            if (data.success) {
                                $self.newOwner("");
                                $self.refresh();
                            }

                            if (data.message != null) {
                                $self.message(data.message);
                            }
                        }
                    })
                    .fail(function (jqXhr, textStatus, errorThrown) {
                        alert("Error: " + errorThrown);
                    });
                };

                this.removeOwner = function (owner, prefix) {
                    if (!confirm('Are you sure you want to remove this owner?')) {
                        e.preventDefault();
                    }

                    var obj = {
                        prefix: prefix,
                        owner: owner,
                    };

                    $self.message("");
                    $.ajax({
                        url: '@Url.Action("RemoveOwner", "ReservedNamespace", new { area = "Admin" })',
                        cache: false,
                        dataType: 'json',
                        type: 'POST',
                        data: window.nuget.addAjaxAntiForgeryToken(obj),
                        success: function (data) {
                            if (data.success) {
                                $self.refresh();
                            }

                            if (data.message != null) {
                                $self.message(data.message);
                            }
                        }
                    })
                    .fail(function (jqXhr, textStatus, errorThrown) {
                        alert("Error: " + errorThrown);
                    });
                };

                this.generateValue = function (user, subscription) {
                    return JSON.stringify({ "u": user.Username, "g": subscription, "v": user.Selected[subscription]() })
                };

                this.generateUserUrl = function (user) {
                    return '/profiles/' + user;
                };

                this.generatePattern = function (value, isPrefix) {
                    return isPrefix ? value + "*" : value;
                };
            };

            ko.applyBindings(new viewModel(), $('.main-container').get(0));
        });
    </script>
}